const OrderStatus = cc.Enum({
    All: 0,//全部订单
    Wait: 1,//待开奖订单
    Win:2,//中奖订单
    Chase:3//追号订单
});

/*
用户界面
*/ 
cc.Class({
    extends: cc.Component,

    properties: {
        spUserHead: {
            default: null,
            type: cc.Sprite
        },
        spBaseHead:{
            default: null,
            type: cc.SpriteFrame
        },

        btnRealName:{
            default: null,
            type: cc.Button
        },
     
        labViplevel:{
            default: null,
            type: cc.Label
        },

        ndVip:{
            default: null,
            type: cc.Node
        },

        spCommon:{
            default: null,
            type: cc.Node
        },

        labName:{
            default: null,
            type: cc.Label
        },

        labMoney:{
            default: null,
            type: cc.Label
        },

        labAcer:{
            default: null,
            type: cc.Label
        },

        btnRecharge:{
            default: null,
            type: cc.Button
        },

        //订单数组
        toggleGruop:{
            default: [],
            type: cc.Toggle
        },

        //订单item
        orderItemPrefab: {
            default: null,
            type: cc.Prefab
        },

        //订单提示
        ndPrompt:{
            default: null,
            type: cc.Node
        },

        //订单列表
        orderContent:{
            default: [],
            type: cc.Node
        },

        //订单
        scrollview:{
            default:[],
            type:cc.ScrollView
        },

        //订单列表滚动
        ordersList:{
            default: [],
            type: cc.ScrollView
        },

        //订单详情
        userOrderDetil: {
            default: null,
            type: cc.Prefab
        },

        //追号订单列表
        userFollowOrderDetil: {
            default: null,
            type: cc.Prefab
        },

        userInformationPop: {
            default: null,
            type: cc.Prefab
        },
        
        userRechargePop: {
            default: null,
            type: cc.Prefab
        },

        userGetBankCashPop: {
            default: null,
            type: cc.Prefab
        },

        userAccountRecordPop:{
            default: null,
            type: cc.Prefab
        },

        userVerifiedPop:{
            default: null,
            type: cc.Prefab
        },

        userSettingPop:{
            default: null,
            type: cc.Prefab
        },

          //修改昵称page
        modifyNamePrefab:{
            default: null,
            type: cc.Prefab
        },

        //修改提现密码
        modifyPwdPrefab:{
            default: null,
            type: cc.Prefab
        },

        ndOther:{
            default: null,
            type: cc.Node
        },
        tgOther:{
            default: null,
            type: cc.Node
        },

        labAllOrder:{
            default:[],
            type:cc.Label
        },
        
        ndRechargeBtns:{
            default:null,
            type:cc.Node
        },

        //彩券
        userRedPop:{
            default:null,
            type:cc.Prefab
        },

        _orderLists:[],//订单列表指针
        _indexPageNumber:[],//页
        _indexRowsPerPage:[],//行
        _currentOrderList:null,//当前显示订单列表
        _currentOrderStatus:0,//当前订单下标
        _isNowRefreshing:false,//是否正在加载新列表

        orderTime:"",//临时记录订单最后一栏时间

        _isopen:false,

    },

    // use this for initialization
    onLoad: function () {   
        if(User.getAppState() == 0)
        {
            this.ndRechargeBtns.active = false;
        }
        this._isNowRefreshing = false;
        window.Notification.on('USER_useruirefresh', function (event) {
            this.refreshInfo();
        },this);

        this.ndOther.on(cc.Node.EventType.TOUCH_END, function (event) {
            if(!this.ndOther.active)
                return;
            var contentRect = this.tgOther.getBoundingBoxToWorld();
            var touchLocation = event.getLocation();
            if(cc.rectContainsPoint(contentRect, touchLocation) == false){//关闭
                this.ndOther.active = false;
            }
        }, this);
        for(var i =0;i<this.toggleGruop.length;i++)
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "UserUI"
            checkEventHandler.handler = "onOrderChange";
            checkEventHandler.customEventData = i;
            this.toggleGruop[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
    },

    //切换到其他界面清空订单列表
    deleteOrder:function(){
        this.orderContent[0].removeAllChildren();
    },

    //获取服务器信息刷新
    requestRefresh:function(){
        var recv = function recv(ret) {
            if (ret.Code !== 0) {
                cc.error(ret.Msg);
            } else {
                if(this._isopen == false)
                {
                    this._isopen = true;
                    User.setUserCode(ret.Data.UserCode);
                }

                User.setNickName(ret.Data.Nick);
                User.setTel(ret.Data.Mobie);
                User.setBalance(ret.Data.Balance);
                User.setGoldBean(ret.Data.Gold);
                User.setIsrobot(ret.Data.IsRobot);
                User.setAvataraddress(ret.Data.AvatarUrl);
                User.setVipLevel(ret.Data.VIP);
                User.setFullName(ret.Data.FullName);
                User.setIsCertification(ret.Data.IsCertification);
                User.setLoginToken(ret.Data.Token);
                User.setIsWithdrawPwd(ret.Data.IsWithdrawPwd);

            }
            
            this.labName.string = User.getNickName();
            if(User.getVipLevel()>0)
            {
                this.labViplevel.string = User.getVipLevel();
                this.ndVip.active = true;
                this.spCommon.active = false;
            }
            else
            {
                this.ndVip.active = false;
                this.spCommon.active = true;
            }
            this.labMoney.string = User.getBalance().toFixed(2)+"元";
            
            try {
                this.labAcer.string = ret.Data.CouponsCount + "个";
            } catch (error) {
                this.labAcer.string = "0个";
            }
            
            if(User.getIsCertification())
            {
                this.btnRealName.node.getChildByName("spSelected").active = true;
            }
            else
            {
                this.btnRealName.node.getChildByName("spSelected").active = false;
            }
            //头像动态加载
            var url = User.getAvataraddress();
            //cc.log("init my logo1:"+url);
            if(url != "" && url != null &&typeof(url) != "undefined"){
                //cc.log("init my logo2:"+url);
                cc.loader.load({url, type:"jpg"}, function(err, tex){
                    //cc.log("init my logo3:"+tex);
                    if(tex != null){
                        var sf = new cc.SpriteFrame(tex);
                        this.spUserHead.getComponent(cc.Sprite).spriteFrame = sf;
                        this.spUserHead.node.width = 180;
                        this.spUserHead.node.height = 180;
                    }
                    else
                    {
                        this.spUserHead.getComponent(cc.Sprite).spriteFrame = this.spBaseHead;
                        this.spUserHead.node.width = 180;
                        this.spUserHead.node.height = 180;
                    }
                }.bind(this));
            }
            else
            {
                this.spUserHead.getComponent(cc.Sprite).spriteFrame = this.spBaseHead;
                this.spUserHead.node.width = 180;
                this.spUserHead.node.height = 180;
            }

            this.tgOther.getChildByName("tgAllOrder").getComponent(cc.Toggle).isChecked = true;
            this.tgOther.getChildByName("tgFollowOrder").getComponent(cc.Toggle).isChecked = false;
            this.labAllOrder[0].string = "全部订单";
            this.labAllOrder[1].string = "全部订单";
            
            for(var i=0;i<this.toggleGruop.length;i++)
            {
                if(i==0)
                {
                    this.toggleGruop[i].getComponent(cc.Toggle).isChecked = true;
                    this.changeOrder(i); 
                }
                else
                {
                    this.toggleGruop[i].getComponent(cc.Toggle).isChecked = false;
                }
                
            }
        }.bind(this);

        var data = {
            Token:User.getLoginToken(),
            UserCode:User.getUserCode(),
        };
        CL.HTTP.sendRequestRet(DEFINE.HTTP_MESSAGE.GETUSERINFO, data, recv.bind(this),"POST"); 
    },

    //数据初始化
    refreshInfo: function() {
        this.requestRefresh();
    },

    //入口 重置刷新
    resetRefresh: function(){
        this._indexPageNumber = [1, 1, 1, 1];
        this._indexRowsPerPage = [11, 11, 11, 11];
      
        this.refreshInfo();
    },

    onOrderChange:function(toggle,customEventData){
        if(toggle.getComponent(cc.Toggle).isChecked )
        {
            this.changeOrder(customEventData);
        }
        else
        {
            if(customEventData == 0)
            {
                this.ndOther.active = true;
            }
            toggle.getComponent(cc.Toggle).isChecked = true;
        } 
    },

    onOtherOrderChange:function(toggle,customEventData){  
        this.ndOther.active = false;
        this.labAllOrder[0].string = (customEventData == 0)?"全部订单":"追号订单";
        this.labAllOrder[1].string = (customEventData == 0)?"全部订单":"追号订单";
        this.changeOrder(0);
    },

    //切换订单页
    changeOrder:function(index){
        var idx = index;
        if(index==OrderStatus.All )
        {
            idx = (this.labAllOrder[0].string == "全部订单")?OrderStatus.All:OrderStatus.Chase;
        }
         
        this.ndPrompt.active = false;
        this.orderTime = "";
        this.orderContent[index].removeAllChildren();
        this.scrollview[index].scrollToTop(0.1);
        var recv = function recv(ret) { 
            ComponentsUtils.unblock();
            this._indexPageNumber[idx] = 2; 
            if(ret.Code == 0 || ret.Code == 49)
            {
               var obj = ret.Data;
               if(obj == null || obj.length <= 0)
               {
                   this.ndPrompt.active = true;
                   return;
               }
               else
               {
                   this.ndPrompt.active = false;
               }
               var month = 0;
               var day = 0;   
               var show = true;  
               var temp = this.orderTime == ""?"":this.orderTime;
               for(var i = 0;i < obj.length;i++)
               {
                   var time = obj[i].OrderTime;
                   var month = time.slice(4,6); 
                   var day = time.slice(6,8); 
                   if(temp == "")
                   {
                       temp = month+day;
                   }
                   else
                   {
                       if(temp == month+day)
                       {
                           show = false;
                       }
                       else
                       {
                           temp = month+day;
                           show = true;
                       }
                   } 
                    this.orderTime = temp;
                   var item = cc.instantiate(this.orderItemPrefab); 
                   item.getComponent('user_order_item').init({
                        LotteryName: obj[i].LotteryName,
                        State: obj[i].OrderStatus,
                        Money: LotteryUtils.moneytoServer(obj[i].Amount),
                        Month: show?month:0,
                        Day: show?day:0,
                        type: LotteryUtils.getOrderByBuyType(obj[i].BuyType),
                        IsuseNum: obj[i].IsuseNum,
                   });   
                    var clickEventHandler = new cc.Component.EventHandler();
                    clickEventHandler.target = this.node; 
                    clickEventHandler.component = "UserUI"
                    clickEventHandler.handler = "onClickCallBack";
                    clickEventHandler.customEventData = {code:obj[i].OrderCode,type:obj[i].BuyType};
                    item.getComponent(cc.Button).clickEvents.push(clickEventHandler);
                    
                    this.orderContent[index].addChild(item); 
               }

            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);
        
        var data = {
            Token:User.getLoginToken(),
            UserCode:User.getUserCode(),
            OrderStatus:idx,
            PageNumber:1,
            RowsPerPage:11,
        };
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETORDERRECORDLIST, data, recv.bind(this),"POST");    
        ComponentsUtils.block();
    },

    

    //列表回调
    onClickCallBack:function(event, customEventData){
        if(customEventData.type == 0 || customEventData.type == 2)
        {
            var recv = function recv(ret) { 
                ComponentsUtils.unblock();
                if(ret.Code == 0)
                {
                    if(ret.Data.LotteryCode == 40010 || ret.Data.LotteryCode == 40020 )
                    {
                        ComponentsUtils.showTips("该彩种当前版本不存在");
                        return;
                    }
                    var canvas = cc.find("Canvas");
                    var userOrderDetil = cc.instantiate(this.userOrderDetil);
                    userOrderDetil.getComponent('user_order_detail_pop').init(ret.Data,0,customEventData.code,0);
                    canvas.addChild(userOrderDetil);
                }
                else
                {
                    ComponentsUtils.showTips(ret.Msg);
                }
            }.bind(this);
            var data = {
                Token:User.getLoginToken(),
                UserCode:User.getUserCode(),
                OrderCode:customEventData.code,
                SchemeDetail:""
            };
            CL.HTTP.sendRequestRet(DEFINE.HTTP_MESSAGE.GETORDERDETAILS, data, recv.bind(this),"POST");    
            ComponentsUtils.block();
        }
        else if(customEventData.type == 1)
        {
             var recv = function recv(ret) { 
                ComponentsUtils.unblock();
                if(ret.Code == 0)
                {
                    var canvas = cc.find("Canvas");
                    var userFollowOrderDetil = cc.instantiate(this.userFollowOrderDetil);
                    userFollowOrderDetil.getComponent('user_followOrder_detail_pop').init(ret.Data,customEventData.code);
                    canvas.addChild(userFollowOrderDetil);
                }
                else
                {
                    ComponentsUtils.showTips(ret.Msg);
                }
            }.bind(this);
            var data = {
                Token:User.getLoginToken(),
                UserCode:User.getUserCode(),
                OrderCode:customEventData.code,
            };
            CL.HTTP.sendRequestRet(DEFINE.HTTP_MESSAGE.GETADDTOLIST, data, recv.bind(this),"POST");    
            ComponentsUtils.block();
        }
       
    },

    //滚动获取下一页
    scrollCallBack: function (scrollview, eventType, customEventData) {
        if(eventType === cc.ScrollView.EventType.BOUNCE_BOTTOM)
        {
            //cc.log("UserUI 订单列表：BOUNCE_BOTTOM");
            //下拉刷新,当底部的offset抵达到某个点的时候
            var offset_y = scrollview.getScrollOffset().y;
            var max_y = scrollview.getMaxScrollOffset().y; 
            if(offset_y - max_y>200){
                if(this._isNowRefreshing == false && OrderStatus.Wait != customEventData){
                    
                    var custom = customEventData;
                    if(customEventData == OrderStatus.All)
                        custom = this.labAllOrder[0].string == "全部订单" ?OrderStatus.All:OrderStatus.Chase;
                    //cc.log("UserUI 订单列表：刷新："+custom );
                    this.nextOrderList(this.orderContent[customEventData],custom);
                    this._isNowRefreshing = true;
                } 
            }
        }
    },

    //下拉刷新
    scrollRefresh: function (scrollview, eventType, customEventData) {
        if(eventType === cc.ScrollView.EventType.BOUNCE_TOP)
        {
            //下拉刷新,当底部的offset抵达到某个点的时候
            var offset_y = scrollview.getScrollOffset().y;
            var max_y = scrollview.getMaxScrollOffset().y; 
            if(max_y - offset_y >200){
                //cc.log("userUI 订单列表：刷新：");
                this.resetRefresh();
            }
        }
    },

    //加载下一页信息
    nextOrderList:function(rootLayer,index){
     var self = this;
        var content = rootLayer;
        var clen = content.childrenCount;
        var recv = function recv(ret) { 
             ComponentsUtils.unblock();
            if(ret.Code == 0 )
            {
               var obj = ret.Data;
               if(obj == null || obj.length <= 0)
               {
                    this.node.runAction(cc.sequence(cc.delayTime(2), cc.callFunc(function(){
                         this._isNowRefreshing = false;   
                    }.bind(this))));
                   return;
               }
               
               var month = 0;  
               var show = true; 
               var day = 0;
               var temp = this.orderTime == ""?"":this.orderTime;
               for(var i = 0;i < obj.length;i++)
               {
                   var time = obj[i].OrderTime;
                   month = time.slice(4,6); 
                   day = time.slice(6,8); 
                   if(temp == "")
                   {
                       temp = month+day;
                   }
                   else
                   {
                       if(temp == month+day)
                       {
                           show = false;
                       }
                       else
                       {
                           temp = month+day;
                           show = true;
                       }
                   } 
                   this.orderTime = temp;
                   var item = cc.instantiate(self.orderItemPrefab);
                   item.getComponent('user_order_item').init({
                        LotteryName: obj[i].LotteryName,
                        State: obj[i].OrderStatus,
                        Money: LotteryUtils.moneytoServer(obj[i].Amount),
                        Month: show?month:0,
                        Day: show?day:0,
                        type: LotteryUtils.getOrderByBuyType(obj[i].BuyType),
                        IsuseNum: obj[i].IsuseNum,
                   });   
                    var clickEventHandler = new cc.Component.EventHandler();
                    clickEventHandler.target = this.node; 
                    clickEventHandler.component = "UserUI"
                    clickEventHandler.handler = "onClickCallBack";
                    clickEventHandler.customEventData = {code:obj[i].OrderCode,type:obj[i].BuyType};
                    item.getComponent(cc.Button).clickEvents.push(clickEventHandler);
                    content.addChild(item);      
               }
               this._indexPageNumber[index] += 1; 
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
            this._isNowRefreshing = false;
        }.bind(this);
        
        var data = {
            Token:User.getLoginToken(),
            UserCode:User.getUserCode(),
            OrderStatus:index,
            PageNumber:this._indexPageNumber[index],
            RowsPerPage:this._indexRowsPerPage[index],
        };
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETORDERRECORDLIST, data, recv.bind(this),"POST");    
        ComponentsUtils.block();
    },

    //客服
    onService: function() {
        var confirmCallback = function(){
        }.bind(this);
        ComponentsUtils.showAlertTips(4, "尊敬的会员您好！欢迎来到彩乐彩票。如有疑问请拨打客户热线 020-85200475", null, "联系客服", confirmCallback, "确定");
    },

     //设置
    onSetting: function() {
        var canvas = cc.find("Canvas");
        var userSetting = cc.instantiate(this.userSettingPop);
        canvas.addChild(userSetting);
        userSetting.active = true;
    },

    //前往登录
    onGotoLogin:function(){
        var canvas = cc.find("Canvas");
        var loginPop = cc.instantiate(this._loginPopPrefab);
        canvas.addChild(loginPop);
        loginPop.getComponent("Login_Pop").setCallBack(callBack);
    },

    //前往信息页
    onGotoUserInformationBtn: function() {
        var canvas = cc.find("Canvas");
        var userInformation = cc.instantiate(this.userInformationPop);
        canvas.addChild(userInformation);
        
    },

    //前往充值
    onGotoRechargeBtn: function(){
        var canvas = cc.find("Canvas");
        var userRecharge = cc.instantiate(this.userRechargePop);
        canvas.addChild(userRecharge);
        userRecharge.active = true;
    },

    //前往提现
    onGotoBankCashBtn: function(){
        var canvas = cc.find("Canvas");
            if(User.getIsCertification())//实名制
            {
                if(User.getIsWithdrawPwd())//是否存在提现密码
                {
                    var userGetBankCash = cc.instantiate(this.userGetBankCashPop);
                    canvas.addChild(userGetBankCash);
                    userGetBankCash.active = true;
                }
                else
                {   
                    this.onCashPasswordBtn();
                }
            }
            else
            {
                this.onGotoVerifiedBtn();
            }
    },

    //修改提现密码
     onCashPasswordBtn:function(){
        if(User.getIsbindtel())
        {
            var canvas = cc.find("Canvas");
            var modifyPwdPrefab = cc.instantiate(this.modifyPwdPrefab);
            modifyPwdPrefab.getComponent("user_modifyCashPwd_pop").init(2);
            canvas.addChild(modifyPwdPrefab);
            modifyPwdPrefab.active = true;
        }
        else
        {
            this.onGotoBindTelPopBtn();
        }
    },

    //前往账户明细
    onGotoAccountRecordBtn: function(){
        var canvas = cc.find("Canvas");
        var userAccountRecord = cc.instantiate(this.userAccountRecordPop);
        canvas.addChild(userAccountRecord);
        userAccountRecord.active = true;
    },

    //前往实名制
    onGotoVerifiedBtn: function(){
        if(User.getIsCertification())
            return;
        var canvas = cc.find("Canvas");
        var userVerified = cc.instantiate(this.userVerifiedPop);
        canvas.addChild(userVerified);
        userVerified.active = true;
    },

    //前往绑定手机号
    onGotoBindTelPopBtn: function(){
        if(User.getIsbindtel())
            return;
        var canvas = cc.find("Canvas");
        var userVerified = cc.instantiate(this.userVerifiedPop);
        canvas.addChild(userVerified);
        userVerified.active = true;
    },

    //前往修改昵称
    onGotoNickNamePopBtn: function(){
        var canvas = cc.find("Canvas");
        var modifyName = cc.instantiate(this.modifyNamePrefab);
        canvas.addChild(modifyName);
    },

    //前往彩券列表
    onGotoRedPack:function(){
        var canvas = cc.find("Canvas");
        var fpRed = cc.instantiate(this.userRedPop);
        canvas.addChild(fpRed);
    },

    onDestroy: function(){
        window.Notification.offType("USER_informationrefresh");
    },


});
